package edu.buaa.act.anonymous;

import edu.buaa.act.helper.Arguments;
import edu.buaa.act.helper.Utils;
import edu.buaa.act.model.tsc.ValidationTask;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;

/**
 * Created by T7810 on 2017/4/21.
 */
public class Anonymous implements Runnable
{
    private static Logger log = Utils.getDebugLogger();

    private final File inFile;
    private final File outFile;
    private final int k;

    public Anonymous(File input, File output, int k)
    {
        this.inFile = input;
        this.outFile = output;
        this.k = k;
    }

    @Override
    public void run()
    {
        log.debug("run external anonymous program.");
        try {
            if(k==1){
                Files.copy(inFile.toPath(), outFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
                return;
            }
            String nwaPath = ValidationTask.globalConf.get(Arguments.Values.Anonymity_NWA_EXE_Path);
            File program = Utils.getExistFile(nwaPath);
            String[] cmd = new String[]{
                    program.getAbsolutePath(),
                    inFile.getAbsolutePath(),
                    String.valueOf(k),
                    String.valueOf(0),
                    outFile.getAbsolutePath(),
                    "-stats"
            };

            Process p = new ProcessBuilder(cmd).start();

            log.debug("run: "+ cmd2Str(cmd));
            BufferedReader processOutput = new BufferedReader(new InputStreamReader(p.getInputStream()));
            BufferedReader processErrorOutput = new BufferedReader(new InputStreamReader(p.getErrorStream()));

            String output;
            while ((output = processOutput.readLine()) != null) {
                log.debug(output);
            }
            while( processErrorOutput.ready() &&
                    (output = processErrorOutput.readLine()) != null) {
                log.debug(output);
            }
            processErrorOutput.close();
            processOutput.close();

            log.debug("exit({})",p.waitFor());
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private String cmd2Str(String[] cmd){
        String result="";
        for(String p : cmd){
            result += p + " ";
        }
        return result;
    }
}
